<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>

	
		<meta http-equiv="Content-type" content="text/html; charset=UTF-8">
		<meta http-equiv="Content-Language" content="en-us">

		<title>Django | Making queries | Django Documentation</title>

		<meta name="ROBOTS" content="ALL">
		<meta http-equiv="imagetoolbar" content="no">
		<meta name="MSSmartTagsPreventParsing" content="true">
		<meta name="Copyright" content="This site's design and contents Copyright (c) 2005  Lawrence Journal-World.">

		<meta name="keywords" content="Python, Django, framework, open-source">
		<meta name="description" content="Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.">

		<link href="Django%20%7C%20Making%20queries%20%7C%20Django%20Documentation_files/base.css" rel="stylesheet" type="text/css" media="screen">
		<link href="Django%20%7C%20Making%20queries%20%7C%20Django%20Documentation_files/print.css" rel="stylesheet" type="text/css" media="print">
      
  
  <style type="text/css" media="screen">
    #docs-search {
      color: #000;
      float: right;
    }
    #docs-search form {
      font-size: 92%;
      margin: 0;
      padding: 1em 1em 0;
      white-space: nowrap;
    }
    form.search ul {
      list-style: none;
      margin: 0;
      padding: 0;
    }
    form.search li {
      display: inline;
      padding-right: 1em;
    }
    form.search .query {
      width: 18em;
    }
  </style>
  <link rel="stylesheet" href="Django%20%7C%20Making%20queries%20%7C%20Django%20Documentation_files/pygments.css" type="text/css">

	</head><body id="documentation" class="default">

	<div id="container">
		<div id="header">
			<h1 id="logo"><a href="http://www.djangoproject.com/"><img src="Django%20%7C%20Making%20queries%20%7C%20Django%20Documentation_files/hdr_logo.gif" alt="Django"></a></h1>
			<ul id="nav-global">
				<li id="nav-homepage"><a href="http://www.djangoproject.com/">Home</a></li>
				<li id="nav-download"><a href="http://www.djangoproject.com/download/">Download</a></li>
				<li id="nav-documentation"><a href="http://docs.djangoproject.com/">Documentation</a></li>
				<li id="nav-weblog"><a href="http://www.djangoproject.com/weblog/">Weblog</a></li>
				<li id="nav-community"><a href="http://www.djangoproject.com/community/">Community</a></li>
				<li id="nav-code"><a href="http://code.djangoproject.com/">Code</a></li>
			</ul>
		</div>
		<!-- END Header -->
		<div id="billboard">
  <h2><a href="http://docs.djangoproject.com/en/1.0/">Django documentation</a></h2>
</div>
		<div id="columnwrap">
			
		<div id="content-main">
		


  <h2 class="deck">
  
    This document describes Django version 1.0. For development documentation, 
    <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/">go here</a>.
  
  </h2>
  <div class="section" id="s-making-queries">
<span id="s-topics-db-queries"></span><span id="making-queries"></span><span id="topics-db-queries"></span><h1>Making queries<a class="headerlink" href="#making-queries" title="Permalink to this headline">¶</a></h1>
<p>Once you’ve created your <a class="reference external" href="http://docs.djangoproject.com/en/1.0/topics/db/models/#topics-db-models"><em>data models</em></a>, Django
automatically gives you a database-abstraction API that lets you create,
retrieve, update and delete objects. This document explains how to use this
API. Refer to the <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/models/#ref-models-index"><em>data model reference</em></a> for full
details of all the various model lookup options.</p>
<p>Throughout this guide (and in the reference), we’ll refer to the following
models, which comprise a weblog application:</p>
<div class="highlight-python" id="queryset-model-example"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Blog</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mf">100</span><span class="p">)</span>
    <span class="n">tagline</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">TextField</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">__unicode__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span>

<span class="k">class</span> <span class="nc">Author</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mf">50</span><span class="p">)</span>
    <span class="n">email</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">EmailField</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">__unicode__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span>

<span class="k">class</span> <span class="nc">Entry</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">blog</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Blog</span><span class="p">)</span>
    <span class="n">headline</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mf">255</span><span class="p">)</span>
    <span class="n">body_text</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">TextField</span><span class="p">()</span>
    <span class="n">pub_date</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateTimeField</span><span class="p">()</span>
    <span class="n">authors</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span><span class="n">Author</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__unicode__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">headline</span>
</pre></div>
</div>
<div class="section" id="s-creating-objects">
<span id="creating-objects"></span><h2>Creating objects<a class="headerlink" href="#creating-objects" title="Permalink to this headline">¶</a></h2>
<p>To represent database-table data in Python objects, Django uses an intuitive
system: A model class represents a database table, and an instance of that
class represents a particular record in the database table.</p>
<p>To create an object, instantiate it using keyword arguments to the model class,
then call <tt class="docutils literal"><span class="pre">save()</span></tt> to save it to the database.</p>
<p>You import the model class from wherever it lives on the Python path, as you
may expect. (We point this out here because previous Django versions required
funky model importing.)</p>
<p>Assuming models live in a file <tt class="docutils literal"><span class="pre">mysite/blog/models.py</span></tt>, here's an example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">from</span> <span class="nn">mysite.blog.models</span> <span class="k">import</span> <span class="n">Blog</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">Blog</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">'Beatles Blog'</span><span class="p">,</span> <span class="n">tagline</span><span class="o">=</span><span class="s">'All the latest Beatles news.'</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>This performs an <tt class="docutils literal"><span class="pre">INSERT</span></tt> SQL statement behind the scenes. Django doesn't hit
the database until you explicitly call <tt class="docutils literal"><span class="pre">save()</span></tt>.</p>
<p>The <tt class="docutils literal"><span class="pre">save()</span></tt> method has no return value.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<p><tt class="docutils literal"><span class="pre">save()</span></tt> takes a number of advanced options not described here.
See the documentation for <tt class="docutils literal"><span class="pre">save()</span></tt> for complete details.</p>
<p class="last">To create an object and save it all in one step see the <tt class="docutils literal"><span class="pre">`create()`</span></tt>
method.</p>
</div>
</div>
<div class="section" id="s-saving-changes-to-objects">
<span id="saving-changes-to-objects"></span><h2>Saving changes to objects<a class="headerlink" href="#saving-changes-to-objects" title="Permalink to this headline">¶</a></h2>
<p>To save changes to an object that's already in the database, use <tt class="docutils literal"><span class="pre">save()</span></tt>.</p>
<p>Given a <tt class="docutils literal"><span class="pre">Blog</span></tt> instance <tt class="docutils literal"><span class="pre">b5</span></tt> that has already been saved to the database,
this example changes its name and updates its record in the database:</p>
<div class="highlight-python"><pre>&gt;&gt; b5.name = 'New name'
&gt;&gt; b5.save()</pre>
</div>
<p>This performs an <tt class="docutils literal"><span class="pre">UPDATE</span></tt> SQL statement behind the scenes. Django doesn't hit
the database until you explicitly call <tt class="docutils literal"><span class="pre">save()</span></tt>.</p>
<div class="section" id="s-saving-foreignkey-and-manytomanyfield-fields">
<span id="saving-foreignkey-and-manytomanyfield-fields"></span><h3>Saving <tt class="docutils literal"><span class="pre">ForeignKey</span></tt> and <tt class="docutils literal"><span class="pre">ManyToManyField</span></tt> fields<a class="headerlink" href="#saving-foreignkey-and-manytomanyfield-fields" title="Permalink to this headline">¶</a></h3>
<p>Updating <tt class="docutils literal"><span class="pre">ForeignKey</span></tt> fields works exactly the same way as saving a normal
field; simply assign an object of the right type to the field in question:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">cheese_blog</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">"Cheddar Talk"</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">entry</span><span class="o">.</span><span class="n">blog</span> <span class="o">=</span> <span class="n">cheese_blog</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">entry</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>Updating a <tt class="docutils literal"><span class="pre">ManyToManyField</span></tt> works a little differently; use the <tt class="docutils literal"><span class="pre">add()</span></tt>
method on the field to add a record to the relation:</p>
<div class="highlight-python"><pre>&gt;&gt; joe = Author.objects.create(name="Joe")
&gt;&gt; entry.authors.add(joe)</pre>
</div>
<p>Django will complain if you try to assign or add an object of the wrong type.</p>
</div>
</div>
<div class="section" id="s-retrieving-objects">
<span id="retrieving-objects"></span><h2>Retrieving objects<a class="headerlink" href="#retrieving-objects" title="Permalink to this headline">¶</a></h2>
<p>To retrieve objects from your database, you construct a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> via a
<tt class="docutils literal"><span class="pre">Manager</span></tt> on your model class.</p>
<p>A <tt class="docutils literal"><span class="pre">QuerySet</span></tt> represents a collection of objects from your database. It can
have zero, one or many <em>filters</em> -- criteria that narrow down the collection
based on given parameters. In SQL terms, a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> equates to a <tt class="docutils literal"><span class="pre">SELECT</span></tt>
statement, and a filter is a limiting clause such as <tt class="docutils literal"><span class="pre">WHERE</span></tt> or <tt class="docutils literal"><span class="pre">LIMIT</span></tt>.</p>
<p>You get a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> by using your model's <tt class="docutils literal"><span class="pre">Manager</span></tt>. Each model has at
least one <tt class="docutils literal"><span class="pre">Manager</span></tt>, and it's called <tt class="docutils literal"><span class="pre">objects</span></tt> by default. Access it
directly via the model class, like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span>
<span class="go">&lt;django.db.models.manager.Manager object at ...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">Blog</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">'Foo'</span><span class="p">,</span> <span class="n">tagline</span><span class="o">=</span><span class="s">'Bar'</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">objects</span>
<span class="go">Traceback:</span>
<span class="go">    ...</span>
<span class="go">AttributeError: "Manager isn't accessible via Blog instances."</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><tt class="docutils literal"><span class="pre">Managers</span></tt> are accessible only via model classes, rather than from model
instances, to enforce a separation between "table-level" operations and
"record-level" operations.</p>
</div>
<p>The <tt class="docutils literal"><span class="pre">Manager</span></tt> is the main source of <tt class="docutils literal"><span class="pre">QuerySets</span></tt> for a model. It acts as a
"root" <tt class="docutils literal"><span class="pre">QuerySet</span></tt> that describes all objects in the model's database table.
For example, <tt class="docutils literal"><span class="pre">Blog.objects</span></tt> is the initial <tt class="docutils literal"><span class="pre">QuerySet</span></tt> that contains all
<tt class="docutils literal"><span class="pre">Blog</span></tt> objects in the database.</p>
<div class="section" id="s-retrieving-all-objects">
<span id="retrieving-all-objects"></span><h3>Retrieving all objects<a class="headerlink" href="#retrieving-all-objects" title="Permalink to this headline">¶</a></h3>
<p>The simplest way to retrieve objects from a table is to get all of them.
To do this, use the <tt class="docutils literal"><span class="pre">all()</span></tt> method on a <tt class="docutils literal"><span class="pre">Manager</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">all_entries</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">all()</span></tt> method returns a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> of all the objects in the database.</p>
<p>(If <tt class="docutils literal"><span class="pre">Entry.objects</span></tt> is a <tt class="docutils literal"><span class="pre">QuerySet</span></tt>, why can't we just do <tt class="docutils literal"><span class="pre">Entry.objects</span></tt>?
That's because <tt class="docutils literal"><span class="pre">Entry.objects</span></tt>, the root <tt class="docutils literal"><span class="pre">QuerySet</span></tt>, is a special case
that cannot be evaluated. The <tt class="docutils literal"><span class="pre">all()</span></tt> method returns a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> that
<em>can</em> be evaluated.)</p>
</div>
<div class="section" id="s-retrieving-specific-objects-with-filters">
<span id="retrieving-specific-objects-with-filters"></span><h3>Retrieving specific objects with filters<a class="headerlink" href="#retrieving-specific-objects-with-filters" title="Permalink to this headline">¶</a></h3>
<p>The root <tt class="docutils literal"><span class="pre">QuerySet</span></tt> provided by the <tt class="docutils literal"><span class="pre">Manager</span></tt> describes all objects in the
database table. Usually, though, you'll need to select only a subset of the
complete set of objects.</p>
<p>To create such a subset, you refine the initial <tt class="docutils literal"><span class="pre">QuerySet</span></tt>, adding filter
conditions. The two most common ways to refine a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> are:</p>
<dl class="docutils">
<dt><tt class="docutils literal"><span class="pre">filter(**kwargs)</span></tt></dt>
<dd>Returns a new <tt class="docutils literal"><span class="pre">QuerySet</span></tt> containing objects that match the given
lookup parameters.</dd>
<dt><tt class="docutils literal"><span class="pre">exclude(**kwargs)</span></tt></dt>
<dd>Returns a new <tt class="docutils literal"><span class="pre">QuerySet</span></tt> containing objects that do <em>not</em> match the
given lookup parameters.</dd>
</dl>
<p>The lookup parameters (<tt class="docutils literal"><span class="pre">**kwargs</span></tt> in the above function definitions) should
be in the format described in <a class="reference internal" href="#field-lookups">Field lookups</a> below.</p>
<p>For example, to get a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> of blog entries from the year 2006, use
<tt class="docutils literal"><span class="pre">filter()</span></tt> like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mf">2006</span><span class="p">)</span>
</pre></div>
</div>
<p>We don't have to add an <tt class="docutils literal"><span class="pre">all()</span></tt> -- <tt class="docutils literal"><span class="pre">Entry.objects.all().filter(...)</span></tt>. That
would still work, but you only need <tt class="docutils literal"><span class="pre">all()</span></tt> when you want all objects from the
root <tt class="docutils literal"><span class="pre">QuerySet</span></tt>.</p>
<div class="section" id="s-id1">
<span id="s-chaining-filters"></span><span id="id1"></span><span id="chaining-filters"></span><h4>Chaining filters<a class="headerlink" href="#id1" title="Permalink to this headline">¶</a></h4>
<p>The result of refining a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> is itself a <tt class="docutils literal"><span class="pre">QuerySet</span></tt>, so it's
possible to chain refinements together. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">headline__startswith</span><span class="o">=</span><span class="s">'What'</span>
<span class="gp">... </span><span class="p">)</span><span class="o">.</span><span class="n">exclude</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">pub_date__gte</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span>
<span class="gp">... </span><span class="p">)</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">pub_date__gte</span><span class="o">=</span><span class="n">datetime</span><span class="p">(</span><span class="mf">2005</span><span class="p">,</span> <span class="mf">1</span><span class="p">,</span> <span class="mf">1</span><span class="p">)</span>
<span class="gp">... </span><span class="p">)</span>
</pre></div>
</div>
<p>This takes the initial <tt class="docutils literal"><span class="pre">QuerySet</span></tt> of all entries in the database, adds a
filter, then an exclusion, then another filter. The final result is a
<tt class="docutils literal"><span class="pre">QuerySet</span></tt> containing all entries with a headline that starts with "What",
that were published between January 1, 2005, and the current day.</p>
</div>
<div class="section" id="s-id2">
<span id="s-filtered-querysets-are-unique"></span><span id="id2"></span><span id="filtered-querysets-are-unique"></span><h4>Filtered QuerySets are unique<a class="headerlink" href="#id2" title="Permalink to this headline">¶</a></h4>
<p>Each time you refine a <tt class="docutils literal"><span class="pre">QuerySet</span></tt>, you get a brand-new <tt class="docutils literal"><span class="pre">QuerySet</span></tt> that is
in no way bound to the previous <tt class="docutils literal"><span class="pre">QuerySet</span></tt>. Each refinement creates a
separate and distinct <tt class="docutils literal"><span class="pre">QuerySet</span></tt> that can be stored, used and reused.</p>
<p>Example:</p>
<div class="highlight-python"><pre>&gt;&gt; q1 = Entry.objects.filter(headline__startswith="What")
&gt;&gt; q2 = q1.exclude(pub_date__gte=datetime.now())
&gt;&gt; q3 = q1.filter(pub_date__gte=datetime.now())</pre>
</div>
<p>These three <tt class="docutils literal"><span class="pre">QuerySets</span></tt> are separate. The first is a base <tt class="docutils literal"><span class="pre">QuerySet</span></tt>
containing all entries that contain a headline starting with "What". The second
is a subset of the first, with an additional criteria that excludes records
whose <tt class="docutils literal"><span class="pre">pub_date</span></tt> is greater than now. The third is a subset of the first,
with an additional criteria that selects only the records whose <tt class="docutils literal"><span class="pre">pub_date</span></tt> is
greater than now. The initial <tt class="docutils literal"><span class="pre">QuerySet</span></tt> (<tt class="docutils literal"><span class="pre">q1</span></tt>) is unaffected by the
refinement process.</p>
</div>
<div class="section" id="s-id3">
<span id="s-querysets-are-lazy"></span><span id="id3"></span><span id="querysets-are-lazy"></span><h4>QuerySets are lazy<a class="headerlink" href="#id3" title="Permalink to this headline">¶</a></h4>
<p><tt class="docutils literal"><span class="pre">QuerySets</span></tt> are lazy -- the act of creating a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> doesn't involve any
database activity. You can stack filters together all day long, and Django won't
actually run the query until the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> is <em>evaluated</em>. Take a look at
this example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">q</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__startswith</span><span class="o">=</span><span class="s">"What"</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span> <span class="o">=</span> <span class="n">q</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__lte</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span> <span class="o">=</span> <span class="n">q</span><span class="o">.</span><span class="n">exclude</span><span class="p">(</span><span class="n">body_text__icontains</span><span class="o">=</span><span class="s">"food"</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">q</span>
</pre></div>
</div>
<p>Though this looks like three database hits, in fact it hits the database only
once, at the last line (<tt class="docutils literal"><span class="pre">print</span> <span class="pre">q</span></tt>). In general, the results of a <tt class="docutils literal"><span class="pre">QuerySet</span></tt>
aren't fetched from the database until you "ask" for them. When you do, the
<tt class="docutils literal"><span class="pre">QuerySet</span></tt> is <em>evaluated</em> by accessing the database. For more details on
exactly when evaluation takes place, see <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/models/querysets/#when-querysets-are-evaluated"><em>When QuerySets are evaluated</em></a>.</p>
</div>
<div class="section" id="s-other-queryset-methods">
<span id="other-queryset-methods"></span><h4>Other QuerySet methods<a class="headerlink" href="#other-queryset-methods" title="Permalink to this headline">¶</a></h4>
<p>Most of the time you'll use <tt class="docutils literal"><span class="pre">all()</span></tt>, <tt class="docutils literal"><span class="pre">filter()</span></tt> and <tt class="docutils literal"><span class="pre">exclude()</span></tt> when you
need to look up objects from the database. However, that's far from all there is; see the <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/models/querysets/#queryset-api"><em>QuerySet API Reference</em></a> for a complete list
of all the various <tt class="docutils literal"><span class="pre">QuerySet</span></tt> methods.</p>
</div>
</div>
<div class="section" id="s-id4">
<span id="s-limiting-querysets"></span><span id="id4"></span><span id="limiting-querysets"></span><h3>Limiting QuerySets<a class="headerlink" href="#id4" title="Permalink to this headline">¶</a></h3>
<p>Use a subset of Python's array-slicing syntax to limit your <tt class="docutils literal"><span class="pre">QuerySet</span></tt> to a
certain number of results. This is the equivalent of SQL's <tt class="docutils literal"><span class="pre">LIMIT</span></tt> and
<tt class="docutils literal"><span class="pre">OFFSET</span></tt> clauses.</p>
<p>For example, this returns the first 5 objects (<tt class="docutils literal"><span class="pre">LIMIT</span> <span class="pre">5</span></tt>):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()[:</span><span class="mf">5</span><span class="p">]</span>
</pre></div>
</div>
<p>This returns the sixth through tenth objects (<tt class="docutils literal"><span class="pre">OFFSET</span> <span class="pre">5</span> <span class="pre">LIMIT</span> <span class="pre">5</span></tt>):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()[</span><span class="mf">5</span><span class="p">:</span><span class="mf">10</span><span class="p">]</span>
</pre></div>
</div>
<p>Negative indexing (i.e. <tt class="docutils literal"><span class="pre">Entry.objects.all()[-1]</span></tt>) is not supported.</p>
<p>Generally, slicing a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> returns a new <tt class="docutils literal"><span class="pre">QuerySet</span></tt> -- it doesn't
evaluate the query. An exception is if you use the "step" parameter of Python
slice syntax. For example, this would actually execute the query in order to
return a list of every <em>second</em> object of the first 10:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()[:</span><span class="mf">10</span><span class="p">:</span><span class="mf">2</span><span class="p">]</span>
</pre></div>
</div>
<p>To retrieve a <em>single</em> object rather than a list
(e.g. <tt class="docutils literal"><span class="pre">SELECT</span> <span class="pre">foo</span> <span class="pre">FROM</span> <span class="pre">bar</span> <span class="pre">LIMIT</span> <span class="pre">1</span></tt>), use a simple index instead of a
slice. For example, this returns the first <tt class="docutils literal"><span class="pre">Entry</span></tt> in the database, after
ordering entries alphabetically by headline:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">'headline'</span><span class="p">)[</span><span class="mf">0</span><span class="p">]</span>
</pre></div>
</div>
<p>This is roughly equivalent to:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">'headline'</span><span class="p">)[</span><span class="mf">0</span><span class="p">:</span><span class="mf">1</span><span class="p">]</span><span class="o">.</span><span class="n">get</span><span class="p">()</span>
</pre></div>
</div>
<p>Note, however, that the first of these will raise <tt class="docutils literal"><span class="pre">IndexError</span></tt> while the
second will raise <tt class="docutils literal"><span class="pre">DoesNotExist</span></tt> if no objects match the given criteria. See
<tt class="docutils literal"><span class="pre">get()</span></tt> for more details.</p>
</div>
<div class="section" id="s-field-lookups">
<span id="s-field-lookups-intro"></span><span id="field-lookups"></span><span id="field-lookups-intro"></span><h3>Field lookups<a class="headerlink" href="#field-lookups" title="Permalink to this headline">¶</a></h3>
<p>Field lookups are how you specify the meat of an SQL <tt class="docutils literal"><span class="pre">WHERE</span></tt> clause. They're
specified as keyword arguments to the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> methods <tt class="docutils literal"><span class="pre">filter()</span></tt>,
<tt class="docutils literal"><span class="pre">exclude()</span></tt> and <tt class="docutils literal"><span class="pre">get()</span></tt>.</p>
<p>Basic lookups keyword arguments take the form <tt class="docutils literal"><span class="pre">field__lookuptype=value</span></tt>.
(That's a double-underscore). For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__lte</span><span class="o">=</span><span class="s">'2006-01-01'</span><span class="p">)</span>
</pre></div>
</div>
<p>translates (roughly) into the following SQL:</p>
<div class="highlight-python"><pre>SELECT * FROM blog_entry WHERE pub_date &lt;= '2006-01-01';</pre>
</div>
<div class="admonition-how-this-is-possible admonition">
<p class="first admonition-title">How this is possible</p>
<p class="last">Python has the ability to define functions that accept arbitrary name-value
arguments whose names and values are evaluated at runtime. For more
information, see <a class="reference external" href="http://docs.python.org/tut/node6.html#SECTION006720000000000000000">Keyword Arguments</a> in the official Python tutorial.</p>
</div>
<p>If you pass an invalid keyword argument, a lookup function will raise
<tt class="docutils literal"><span class="pre">TypeError</span></tt>.</p>
<p>The database API supports about two dozen lookup types; a complete reference
can be found in the <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/models/querysets/#field-lookups"><em>field lookup reference</em></a>. To give you a taste of what's available, here's some of the more common lookups
you'll probably use:</p>
<dl class="docutils">
<dt><tt class="xref docutils literal"><span class="pre">exact</span></tt></dt>
<dd><p class="first">An "exact" match. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">headline__exact</span><span class="o">=</span><span class="s">"Man bites dog"</span><span class="p">)</span>
</pre></div>
</div>
<p>Would generate SQL along these lines:</p>
<div class="highlight-sql"><div class="highlight"><pre><span class="k">SELECT</span> <span class="p">...</span> <span class="k">WHERE</span> <span class="n">headline</span> <span class="o">=</span> <span class="s1">'Man bites dog'</span><span class="p">;</span>
</pre></div>
</div>
<p>If you don't provide a lookup type -- that is, if your keyword argument
doesn't contain a double underscore -- the lookup type is assumed to be
<tt class="docutils literal"><span class="pre">exact</span></tt>.</p>
<p>For example, the following two statements are equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">id__exact</span><span class="o">=</span><span class="mf">14</span><span class="p">)</span>  <span class="c"># Explicit form</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mf">14</span><span class="p">)</span>         <span class="c"># __exact is implied</span>
</pre></div>
</div>
<p class="last">This is for convenience, because <tt class="docutils literal"><span class="pre">exact</span></tt> lookups are the common case.</p>
</dd>
<dt><tt class="xref docutils literal"><span class="pre">iexact</span></tt></dt>
<dd><p class="first">A case-insensitive match. So, the query:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">name__iexact</span><span class="o">=</span><span class="s">"beatles blog"</span><span class="p">)</span>
</pre></div>
</div>
<p class="last">Would match a <tt class="docutils literal"><span class="pre">Blog</span></tt> titled "Beatles Blog", "beatles blog", or even
"BeAtlES blOG".</p>
</dd>
<dt><tt class="xref docutils literal"><span class="pre">contains</span></tt></dt>
<dd><p class="first">Case-sensitive containment test. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">headline__contains</span><span class="o">=</span><span class="s">'Lennon'</span><span class="p">)</span>
</pre></div>
</div>
<p>Roughly translates to this SQL:</p>
<div class="highlight-sql"><div class="highlight"><pre><span class="k">SELECT</span> <span class="p">...</span> <span class="k">WHERE</span> <span class="n">headline</span> <span class="k">LIKE</span> <span class="s1">'%Lennon%'</span><span class="p">;</span>
</pre></div>
</div>
<p>Note this will match the headline <tt class="docutils literal"><span class="pre">'Today</span> <span class="pre">Lennon</span> <span class="pre">honored'</span></tt> but not
<tt class="docutils literal"><span class="pre">'today</span> <span class="pre">lennon</span> <span class="pre">honored'</span></tt>.</p>
<p class="last">There's also a case-insensitive version, <tt class="xref docutils literal"><span class="pre">icontains</span></tt>.</p>
</dd>
<dt><tt class="xref docutils literal"><span class="pre">startswith</span></tt>, <tt class="xref docutils literal"><span class="pre">endswith</span></tt></dt>
<dd>Starts-with and ends-with search, respectively. There are also
case-insensitive versions called <tt class="xref docutils literal"><span class="pre">istartswith</span></tt> and
<tt class="xref docutils literal"><span class="pre">iendswith</span></tt>.</dd>
</dl>
<p>Again, this only scratches the surface. A complete reference can be found in the
<a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/models/querysets/#field-lookups"><em>field lookup reference</em></a>.</p>
</div>
<div class="section" id="s-lookups-that-span-relationships">
<span id="lookups-that-span-relationships"></span><h3>Lookups that span relationships<a class="headerlink" href="#lookups-that-span-relationships" title="Permalink to this headline">¶</a></h3>
<p>Django offers a powerful and intuitive way to "follow" relationships in
lookups, taking care of the SQL <tt class="docutils literal"><span class="pre">JOIN</span></tt>s for you automatically, behind the
scenes. To span a relationship, just use the field name of related fields
across models, separated by double underscores, until you get to the field you
want.</p>
<p>This example retrieves all <tt class="docutils literal"><span class="pre">Entry</span></tt> objects with a <tt class="docutils literal"><span class="pre">Blog</span></tt> whose <tt class="docutils literal"><span class="pre">name</span></tt>
is <tt class="docutils literal"><span class="pre">'Beatles</span> <span class="pre">Blog'</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog__name__exact</span><span class="o">=</span><span class="s">'Beatles Blog'</span><span class="p">)</span>
</pre></div>
</div>
<p>This spanning can be as deep as you'd like.</p>
<p>It works backwards, too. To refer to a "reverse" relationship, just use the
lowercase name of the model.</p>
<p>This example retrieves all <tt class="docutils literal"><span class="pre">Blog</span></tt> objects which have at least one <tt class="docutils literal"><span class="pre">Entry</span></tt>
whose <tt class="docutils literal"><span class="pre">headline</span></tt> contains <tt class="docutils literal"><span class="pre">'Lennon'</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">entry__headline__contains</span><span class="o">=</span><span class="s">'Lennon'</span><span class="p">)</span>
</pre></div>
</div>
<p>If you are filtering across multiple relationships and one of the intermediate
models doesn't have a value that meets the filter condition, Django will treat
it as if there is an empty (all values are <tt class="docutils literal"><span class="pre">NULL</span></tt>), but valid, object there.
All this means is that no error will be raised. For example, in this filter:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">entry__author__name</span><span class="o">=</span><span class="s">'Lennon'</span><span class="p">)</span>
</pre></div>
</div>
<p>(if there was a related <tt class="docutils literal"><span class="pre">Author</span></tt> model), if there was no <tt class="docutils literal"><span class="pre">author</span></tt>
associated with an entry, it would be treated as if there was also no <tt class="docutils literal"><span class="pre">name</span></tt>
attached, rather than raising an error because of the missing <tt class="docutils literal"><span class="pre">author</span></tt>.
Usually this is exactly what you want to have happen. The only case where it
might be confusing is if you are using <tt class="docutils literal"><span class="pre">isnull</span></tt>. Thus:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">entry__author__name__isnull</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
</pre></div>
</div>
<p>will return <tt class="docutils literal"><span class="pre">Blog</span></tt> objects that have an empty <tt class="docutils literal"><span class="pre">name</span></tt> on the <tt class="docutils literal"><span class="pre">author</span></tt> and
also those which have an empty <tt class="docutils literal"><span class="pre">author</span></tt> on the <tt class="docutils literal"><span class="pre">entry</span></tt>. If you don't want
those latter objects, you could write:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">entry__author__isnull</span><span class="o">=</span><span class="bp">False</span><span class="p">,</span>
        <span class="n">entry__author__name__isnull</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
</pre></div>
</div>
<div class="section" id="s-spanning-multi-valued-relationships">
<span id="spanning-multi-valued-relationships"></span><h4>Spanning multi-valued relationships<a class="headerlink" href="#spanning-multi-valued-relationships" title="Permalink to this headline">¶</a></h4>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>When you are filtering an object based on a <tt class="docutils literal"><span class="pre">ManyToManyField</span></tt> or a reverse
<tt class="docutils literal"><span class="pre">ForeignKeyField</span></tt>, there are two different sorts of filter you may be
interested in. Consider the <tt class="docutils literal"><span class="pre">Blog</span></tt>/<tt class="docutils literal"><span class="pre">Entry</span></tt> relationship (<tt class="docutils literal"><span class="pre">Blog</span></tt> to
<tt class="docutils literal"><span class="pre">Entry</span></tt> is a one-to-many relation). We might be interested in finding blogs
that have an entry which has both <em>"Lennon"</em> in the headline and was published
in 2008. Or we might want to find blogs that have an entry with <em>"Lennon"</em> in
the headline as well as an entry that was published in 2008. Since there are
multiple entries associated with a single <tt class="docutils literal"><span class="pre">Blog</span></tt>, both of these queries are
possible and make sense in some situations.</p>
<p>The same type of situation arises with a <tt class="docutils literal"><span class="pre">ManyToManyField</span></tt>. For example, if
an <tt class="docutils literal"><span class="pre">Entry</span></tt> has a <tt class="docutils literal"><span class="pre">ManyToManyField</span></tt> called <tt class="docutils literal"><span class="pre">tags</span></tt>, we might want to find
entries linked to tags called <em>"music"</em> and <em>"bands"</em> or we might want an
entry that contains a tag with a name of <em>"music"</em> and a status of <em>"public"</em>.</p>
<p>To handle both of these situations, Django has a consistent way of processing
<tt class="docutils literal"><span class="pre">filter()</span></tt> and <tt class="docutils literal"><span class="pre">exclude()</span></tt> calls. Everything inside a single <tt class="docutils literal"><span class="pre">filter()</span></tt>
call is applied simultaneously to filter out items matching all those
requirements. Successive <tt class="docutils literal"><span class="pre">filter()</span></tt> calls further restrict the set of
objects, but for multi-valued relations, they apply to any object linked to
the primary model, not necessarily those objects that were selected by an
earlier <tt class="docutils literal"><span class="pre">filter()</span></tt> call.</p>
<p>That may sound a bit confusing, so hopefully an example will clarify. To
select all blogs that contain entries with both <em>"Lennon"</em> in the headline
and that were published in 2008 (the same entry satisfying both conditions),
we would write:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">entry__headline__contains</span><span class="o">=</span><span class="s">'Lennon'</span><span class="p">,</span>
        <span class="n">entry__pub_date__year</span><span class="o">=</span><span class="mf">2008</span><span class="p">)</span>
</pre></div>
</div>
<p>To select all blogs that contain an entry with <em>"Lennon"</em> in the headline
<strong>as well as</strong> an entry that was published in 2008, we would write:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">entry__headline__contains</span><span class="o">=</span><span class="s">'Lennon'</span><span class="p">)</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span>
        <span class="n">entry__pub_date__year</span><span class="o">=</span><span class="mf">2008</span><span class="p">)</span>
</pre></div>
</div>
<p>In this second example, the first filter restricted the queryset to all those
blogs linked to that particular type of entry. The second filter restricted
the set of blogs <em>further</em> to those that are also linked to the second type of
entry. The entries select by the second filter may or may not be the same as
the entries in the first filter. We are filtering the <tt class="docutils literal"><span class="pre">Blog</span></tt> items with each
filter statement, not the <tt class="docutils literal"><span class="pre">Entry</span></tt> items.</p>
<p>All of this behavior also applies to <tt class="docutils literal"><span class="pre">exclude()</span></tt>: all the conditions in a
single <tt class="docutils literal"><span class="pre">exclude()</span></tt> statement apply to a single instance (if those conditions
are talking about the same multi-valued relation). Conditions in subsequent
<tt class="docutils literal"><span class="pre">filter()</span></tt> or <tt class="docutils literal"><span class="pre">exclude()</span></tt> calls that refer to the same relation may end up
filtering on different linked objects.</p>
</div>
</div>
<div class="section" id="s-the-pk-lookup-shortcut">
<span id="the-pk-lookup-shortcut"></span><h3>The pk lookup shortcut<a class="headerlink" href="#the-pk-lookup-shortcut" title="Permalink to this headline">¶</a></h3>
<p>For convenience, Django provides a <tt class="docutils literal"><span class="pre">pk</span></tt> lookup shortcut, which stands for
"primary key".</p>
<p>In the example <tt class="docutils literal"><span class="pre">Blog</span></tt> model, the primary key is the <tt class="docutils literal"><span class="pre">id</span></tt> field, so these
three statements are equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">id__exact</span><span class="o">=</span><span class="mf">14</span><span class="p">)</span> <span class="c"># Explicit form</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mf">14</span><span class="p">)</span> <span class="c"># __exact is implied</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mf">14</span><span class="p">)</span> <span class="c"># pk implies id__exact</span>
</pre></div>
</div>
<p>The use of <tt class="docutils literal"><span class="pre">pk</span></tt> isn't limited to <tt class="docutils literal"><span class="pre">__exact</span></tt> queries -- any query term
can be combined with <tt class="docutils literal"><span class="pre">pk</span></tt> to perform a query on the primary key of a model:</p>
<div class="highlight-python"><pre># Get blogs entries with id 1, 4 and 7
&gt;&gt;&gt; Blog.objects.filter(pk__in=[1,4,7])

# Get all blog entries with id &gt; 14
&gt;&gt;&gt; Blog.objects.filter(pk__gt=14)</pre>
</div>
<p><tt class="docutils literal"><span class="pre">pk</span></tt> lookups also work across joins. For example, these three statements are
equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog__id__exact</span><span class="o">=</span><span class="mf">3</span><span class="p">)</span> <span class="c"># Explicit form</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog__id</span><span class="o">=</span><span class="mf">3</span><span class="p">)</span>        <span class="c"># __exact is implied</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog__pk</span><span class="o">=</span><span class="mf">3</span><span class="p">)</span>        <span class="c"># __pk implies __id__exact</span>
</pre></div>
</div>
</div>
<div class="section" id="s-escaping-percent-signs-and-underscores-in-like-statements">
<span id="escaping-percent-signs-and-underscores-in-like-statements"></span><h3>Escaping percent signs and underscores in LIKE statements<a class="headerlink" href="#escaping-percent-signs-and-underscores-in-like-statements" title="Permalink to this headline">¶</a></h3>
<p>The field lookups that equate to <tt class="docutils literal"><span class="pre">LIKE</span></tt> SQL statements (<tt class="docutils literal"><span class="pre">iexact</span></tt>,
<tt class="docutils literal"><span class="pre">contains</span></tt>, <tt class="docutils literal"><span class="pre">icontains</span></tt>, <tt class="docutils literal"><span class="pre">startswith</span></tt>, <tt class="docutils literal"><span class="pre">istartswith</span></tt>, <tt class="docutils literal"><span class="pre">endswith</span></tt>
and <tt class="docutils literal"><span class="pre">iendswith</span></tt>) will automatically escape the two special characters used in
<tt class="docutils literal"><span class="pre">LIKE</span></tt> statements -- the percent sign and the underscore. (In a <tt class="docutils literal"><span class="pre">LIKE</span></tt>
statement, the percent sign signifies a multiple-character wildcard and the
underscore signifies a single-character wildcard.)</p>
<p>This means things should work intuitively, so the abstraction doesn't leak.
For example, to retrieve all the entries that contain a percent sign, just use
the percent sign as any other character:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__contains</span><span class="o">=</span><span class="s">'%'</span><span class="p">)</span>
</pre></div>
</div>
<p>Django takes care of the quoting for you; the resulting SQL will look something
like this:</p>
<div class="highlight-sql"><div class="highlight"><pre><span class="k">SELECT</span> <span class="p">...</span> <span class="k">WHERE</span> <span class="n">headline</span> <span class="k">LIKE</span> <span class="s1">'%\%%'</span><span class="p">;</span>
</pre></div>
</div>
<p>Same goes for underscores. Both percentage signs and underscores are handled
for you transparently.</p>
</div>
<div class="section" id="s-id5">
<span id="s-caching-and-querysets"></span><span id="id5"></span><span id="caching-and-querysets"></span><h3>Caching and QuerySets<a class="headerlink" href="#id5" title="Permalink to this headline">¶</a></h3>
<p>Each <tt class="docutils literal"><span class="pre">QuerySet</span></tt> contains a cache, to minimize database access. It's important
to understand how it works, in order to write the most efficient code.</p>
<p>In a newly created <tt class="docutils literal"><span class="pre">QuerySet</span></tt>, the cache is empty. The first time a
<tt class="docutils literal"><span class="pre">QuerySet</span></tt> is evaluated -- and, hence, a database query happens -- Django
saves the query results in the <tt class="docutils literal"><span class="pre">QuerySet</span></tt>'s cache and returns the results
that have been explicitly requested (e.g., the next element, if the
<tt class="docutils literal"><span class="pre">QuerySet</span></tt> is being iterated over). Subsequent evaluations of the
<tt class="docutils literal"><span class="pre">QuerySet</span></tt> reuse the cached results.</p>
<p>Keep this caching behavior in mind, because it may bite you if you don't use
your <tt class="docutils literal"><span class="pre">QuerySet</span></tt>s correctly. For example, the following will create two
<tt class="docutils literal"><span class="pre">QuerySet</span></tt>s, evaluate them, and throw them away:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="p">[</span><span class="n">e</span><span class="o">.</span><span class="n">headline</span> <span class="k">for</span> <span class="n">e</span> <span class="ow">in</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="p">[</span><span class="n">e</span><span class="o">.</span><span class="n">pub_date</span> <span class="k">for</span> <span class="n">e</span> <span class="ow">in</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()]</span>
</pre></div>
</div>
<p>That means the same database query will be executed twice, effectively doubling
your database load. Also, there's a possibility the two lists may not include
the same database records, because an <tt class="docutils literal"><span class="pre">Entry</span></tt> may have been added or deleted
in the split second between the two requests.</p>
<p>To avoid this problem, simply save the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> and reuse it:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">queryset</span> <span class="o">=</span> <span class="n">Poll</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="p">[</span><span class="n">p</span><span class="o">.</span><span class="n">headline</span> <span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">queryset</span><span class="p">]</span> <span class="c"># Evaluate the query set.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="p">[</span><span class="n">p</span><span class="o">.</span><span class="n">pub_date</span> <span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">queryset</span><span class="p">]</span> <span class="c"># Re-use the cache from the evaluation.</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-complex-lookups-with-q-objects">
<span id="complex-lookups-with-q-objects"></span><h2>Complex lookups with Q objects<a class="headerlink" href="#complex-lookups-with-q-objects" title="Permalink to this headline">¶</a></h2>
<p>Keyword argument queries -- in <tt class="docutils literal"><span class="pre">filter()</span></tt>, etc. -- are "AND"ed together. If
you need to execute more complex queries (for example, queries with <tt class="docutils literal"><span class="pre">OR</span></tt>
statements), you can use <tt class="docutils literal"><span class="pre">Q</span></tt> objects.</p>
<p>A <tt class="docutils literal"><span class="pre">Q</span></tt> object (<tt class="docutils literal"><span class="pre">django.db.models.Q</span></tt>) is an object used to encapsulate a
collection of keyword arguments. These keyword arguments are specified as in
"Field lookups" above.</p>
<p>For example, this <tt class="docutils literal"><span class="pre">Q</span></tt> object encapsulates a single <tt class="docutils literal"><span class="pre">LIKE</span></tt> query:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Q</span><span class="p">(</span><span class="n">question__startswith</span><span class="o">=</span><span class="s">'What'</span><span class="p">)</span>
</pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">Q</span></tt> objects can be combined using the <tt class="docutils literal"><span class="pre">&amp;</span></tt> and <tt class="docutils literal"><span class="pre">|</span></tt> operators. When an
operator is used on two <tt class="docutils literal"><span class="pre">Q</span></tt> objects, it yields a new <tt class="docutils literal"><span class="pre">Q</span></tt> object.</p>
<p>For example, this statement yields a single <tt class="docutils literal"><span class="pre">Q</span></tt> object that represents the
"OR" of two <tt class="docutils literal"><span class="pre">"question__startswith"</span></tt> queries:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Q</span><span class="p">(</span><span class="n">question__startswith</span><span class="o">=</span><span class="s">'Who'</span><span class="p">)</span> <span class="o">|</span> <span class="n">Q</span><span class="p">(</span><span class="n">question__startswith</span><span class="o">=</span><span class="s">'What'</span><span class="p">)</span>
</pre></div>
</div>
<p>This is equivalent to the following SQL <tt class="docutils literal"><span class="pre">WHERE</span></tt> clause:</p>
<div class="highlight-python"><pre>WHERE question LIKE 'Who%' OR question LIKE 'What%'</pre>
</div>
<p>You can compose statements of arbitrary complexity by combining <tt class="docutils literal"><span class="pre">Q</span></tt> objects
with the <tt class="docutils literal"><span class="pre">&amp;</span></tt> and <tt class="docutils literal"><span class="pre">|</span></tt> operators and use parenthetical grouping. Also, <tt class="docutils literal"><span class="pre">Q</span></tt>
objects can be negated using the <tt class="docutils literal"><span class="pre">~</span></tt> operator, allowing for combined lookups
that combine both a normal query and a negated (<tt class="docutils literal"><span class="pre">NOT</span></tt>) query:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Q</span><span class="p">(</span><span class="n">question__startswith</span><span class="o">=</span><span class="s">'Who'</span><span class="p">)</span> <span class="o">|</span> <span class="o">~</span><span class="n">Q</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mf">2005</span><span class="p">)</span>
</pre></div>
</div>
<p>Each lookup function that takes keyword-arguments (e.g. <tt class="docutils literal"><span class="pre">filter()</span></tt>,
<tt class="docutils literal"><span class="pre">exclude()</span></tt>, <tt class="docutils literal"><span class="pre">get()</span></tt>) can also be passed one or more <tt class="docutils literal"><span class="pre">Q</span></tt> objects as
positional (not-named) arguments. If you provide multiple <tt class="docutils literal"><span class="pre">Q</span></tt> object
arguments to a lookup function, the arguments will be "AND"ed together. For
example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Poll</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span>
    <span class="n">Q</span><span class="p">(</span><span class="n">question__startswith</span><span class="o">=</span><span class="s">'Who'</span><span class="p">),</span>
    <span class="n">Q</span><span class="p">(</span><span class="n">pub_date</span><span class="o">=</span><span class="n">date</span><span class="p">(</span><span class="mf">2005</span><span class="p">,</span> <span class="mf">5</span><span class="p">,</span> <span class="mf">2</span><span class="p">))</span> <span class="o">|</span> <span class="n">Q</span><span class="p">(</span><span class="n">pub_date</span><span class="o">=</span><span class="n">date</span><span class="p">(</span><span class="mf">2005</span><span class="p">,</span> <span class="mf">5</span><span class="p">,</span> <span class="mf">6</span><span class="p">))</span>
<span class="p">)</span>
</pre></div>
</div>
<p>... roughly translates into the SQL:</p>
<div class="highlight-python"><pre>SELECT * from polls WHERE question LIKE 'Who%'
    AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')</pre>
</div>
<p>Lookup functions can mix the use of <tt class="docutils literal"><span class="pre">Q</span></tt> objects and keyword arguments. All
arguments provided to a lookup function (be they keyword arguments or <tt class="docutils literal"><span class="pre">Q</span></tt>
objects) are "AND"ed together. However, if a <tt class="docutils literal"><span class="pre">Q</span></tt> object is provided, it must
precede the definition of any keyword arguments. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Poll</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span>
    <span class="n">Q</span><span class="p">(</span><span class="n">pub_date</span><span class="o">=</span><span class="n">date</span><span class="p">(</span><span class="mf">2005</span><span class="p">,</span> <span class="mf">5</span><span class="p">,</span> <span class="mf">2</span><span class="p">))</span> <span class="o">|</span> <span class="n">Q</span><span class="p">(</span><span class="n">pub_date</span><span class="o">=</span><span class="n">date</span><span class="p">(</span><span class="mf">2005</span><span class="p">,</span> <span class="mf">5</span><span class="p">,</span> <span class="mf">6</span><span class="p">)),</span>
    <span class="n">question__startswith</span><span class="o">=</span><span class="s">'Who'</span><span class="p">)</span>
</pre></div>
</div>
<p>... would be a valid query, equivalent to the previous example; but:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># INVALID QUERY</span>
<span class="n">Poll</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span>
    <span class="n">question__startswith</span><span class="o">=</span><span class="s">'Who'</span><span class="p">,</span>
    <span class="n">Q</span><span class="p">(</span><span class="n">pub_date</span><span class="o">=</span><span class="n">date</span><span class="p">(</span><span class="mf">2005</span><span class="p">,</span> <span class="mf">5</span><span class="p">,</span> <span class="mf">2</span><span class="p">))</span> <span class="o">|</span> <span class="n">Q</span><span class="p">(</span><span class="n">pub_date</span><span class="o">=</span><span class="n">date</span><span class="p">(</span><span class="mf">2005</span><span class="p">,</span> <span class="mf">5</span><span class="p">,</span> <span class="mf">6</span><span class="p">)))</span>
</pre></div>
</div>
<p>... would not be valid.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">The <a class="reference external" href="http://code.djangoproject.com/browser/django/trunk/tests/modeltests/or_lookups/models.py">OR lookups examples</a> in the Django unit tests show some possible uses
of <tt class="docutils literal"><span class="pre">Q</span></tt>.</p>
</div>
</div>
<div class="section" id="s-comparing-objects">
<span id="comparing-objects"></span><h2>Comparing objects<a class="headerlink" href="#comparing-objects" title="Permalink to this headline">¶</a></h2>
<p>To compare two model instances, just use the standard Python comparison operator,
the double equals sign: <tt class="docutils literal"><span class="pre">==</span></tt>. Behind the scenes, that compares the primary
key values of two models.</p>
<p>Using the <tt class="docutils literal"><span class="pre">Entry</span></tt> example above, the following two statements are equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">some_entry</span> <span class="o">==</span> <span class="n">other_entry</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">some_entry</span><span class="o">.</span><span class="n">id</span> <span class="o">==</span> <span class="n">other_entry</span><span class="o">.</span><span class="n">id</span>
</pre></div>
</div>
<p>If a model's primary key isn't called <tt class="docutils literal"><span class="pre">id</span></tt>, no problem. Comparisons will
always use the primary key, whatever it's called. For example, if a model's
primary key field is called <tt class="docutils literal"><span class="pre">name</span></tt>, these two statements are equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">some_obj</span> <span class="o">==</span> <span class="n">other_obj</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">some_obj</span><span class="o">.</span><span class="n">name</span> <span class="o">==</span> <span class="n">other_obj</span><span class="o">.</span><span class="n">name</span>
</pre></div>
</div>
</div>
<div class="section" id="s-deleting-objects">
<span id="deleting-objects"></span><h2>Deleting objects<a class="headerlink" href="#deleting-objects" title="Permalink to this headline">¶</a></h2>
<p>The delete method, conveniently, is named <tt class="docutils literal"><span class="pre">delete()</span></tt>. This method immediately
deletes the object and has no return value. Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">e</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
</pre></div>
</div>
<p>You can also delete objects in bulk. Every <tt class="docutils literal"><span class="pre">QuerySet</span></tt> has a <tt class="docutils literal"><span class="pre">delete()</span></tt>
method, which deletes all members of that <tt class="docutils literal"><span class="pre">QuerySet</span></tt>.</p>
<p>For example, this deletes all <tt class="docutils literal"><span class="pre">Entry</span></tt> objects with a <tt class="docutils literal"><span class="pre">pub_date</span></tt> year of
2005:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mf">2005</span><span class="p">)</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
</pre></div>
</div>
<p>Keep in mind that this will, whenever possible, be executed purely in
SQL, and so the <tt class="docutils literal"><span class="pre">delete()</span></tt> methods of individual object instances
will not necessarily be called during the process. If you've provided
a custom <tt class="docutils literal"><span class="pre">delete()</span></tt> method on a model class and want to ensure that
it is called, you will need to "manually" delete instances of that
model (e.g., by iterating over a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> and calling <tt class="docutils literal"><span class="pre">delete()</span></tt>
on each object individually) rather than using the bulk <tt class="docutils literal"><span class="pre">delete()</span></tt>
method of a <tt class="docutils literal"><span class="pre">QuerySet</span></tt>.</p>
<p>When Django deletes an object, it emulates the behavior of the SQL
constraint <tt class="docutils literal"><span class="pre">ON</span> <span class="pre">DELETE</span> <span class="pre">CASCADE</span></tt> -- in other words, any objects which
had foreign keys pointing at the object to be deleted will be deleted
along with it. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">b</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mf">1</span><span class="p">)</span>
<span class="c"># This will delete the Blog and all of its Entry objects.</span>
<span class="n">b</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
</pre></div>
</div>
<p>Note that <tt class="docutils literal"><span class="pre">delete()</span></tt> is the only <tt class="docutils literal"><span class="pre">QuerySet</span></tt> method that is not exposed on a
<tt class="docutils literal"><span class="pre">Manager</span></tt> itself. This is a safety mechanism to prevent you from accidentally
requesting <tt class="docutils literal"><span class="pre">Entry.objects.delete()</span></tt>, and deleting <em>all</em> the entries. If you
<em>do</em> want to delete all the objects, then you have to explicitly request a
complete query set:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="s-updating-multiple-objects-at-once">
<span id="updating-multiple-objects-at-once"></span><h2>Updating multiple objects at once<a class="headerlink" href="#updating-multiple-objects-at-once" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>Sometimes you want to set a field to a particular value for all the objects in
a <tt class="docutils literal"><span class="pre">QuerySet</span></tt>. You can do this with the <tt class="docutils literal"><span class="pre">update()</span></tt> method. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># Update all the headlines with pub_date in 2007.</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mf">2007</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">headline</span><span class="o">=</span><span class="s">'Everything is the same'</span><span class="p">)</span>
</pre></div>
</div>
<p>You can only set non-relation fields and <tt class="docutils literal"><span class="pre">ForeignKey</span></tt> fields using this
method, and the value you set the field to must be a hard-coded Python value
(i.e., you can't set a field to be equal to some other field at the moment).</p>
<p>To update <tt class="docutils literal"><span class="pre">ForeignKey</span></tt> fields, set the new value to be the new model
instance you want to point to. Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mf">1</span><span class="p">)</span>

<span class="go"># Change every Entry so that it belongs to this Blog.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">blog</span><span class="o">=</span><span class="n">b</span><span class="p">)</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">update()</span></tt> method is applied instantly and doesn't return anything
(similar to <tt class="docutils literal"><span class="pre">delete()</span></tt>). The only restriction on the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> that is
updated is that it can only access one database table, the model's main
table. So don't try to filter based on related fields or anything like that;
it won't work.</p>
<p>Be aware that the <tt class="docutils literal"><span class="pre">update()</span></tt> method is converted directly to an SQL
statement. It is a bulk operation for direct updates. It doesn't run any
<tt class="docutils literal"><span class="pre">save()</span></tt> methods on your models, or emit the <tt class="docutils literal"><span class="pre">pre_save</span></tt> or <tt class="docutils literal"><span class="pre">post_save</span></tt>
signals (which are a consequence of calling <tt class="docutils literal"><span class="pre">save()</span></tt>). If you want to save
every item in a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> and make sure that the <tt class="docutils literal"><span class="pre">save()</span></tt> method is
called on each instance, you don't need any special function to handle that.
Just loop over them and call <tt class="docutils literal"><span class="pre">save()</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="n">my_queryset</span><span class="p">:</span>
    <span class="n">item</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="s-related-objects">
<span id="related-objects"></span><h2>Related objects<a class="headerlink" href="#related-objects" title="Permalink to this headline">¶</a></h2>
<p>When you define a relationship in a model (i.e., a <tt class="docutils literal"><span class="pre">ForeignKey</span></tt>,
<tt class="docutils literal"><span class="pre">OneToOneField</span></tt>, or <tt class="docutils literal"><span class="pre">ManyToManyField</span></tt>), instances of that model will have
a convenient API to access the related object(s).</p>
<p>Using the models at the top of this page, for example, an <tt class="docutils literal"><span class="pre">Entry</span></tt> object <tt class="docutils literal"><span class="pre">e</span></tt>
can get its associated <tt class="docutils literal"><span class="pre">Blog</span></tt> object by accessing the <tt class="docutils literal"><span class="pre">blog</span></tt> attribute:
<tt class="docutils literal"><span class="pre">e.blog</span></tt>.</p>
<p>(Behind the scenes, this functionality is implemented by Python <a class="reference external" href="http://users.rcn.com/python/download/Descriptor.htm">descriptors</a>.
This shouldn't really matter to you, but we point it out here for the curious.)</p>
<p>Django also creates API accessors for the "other" side of the relationship --
the link from the related model to the model that defines the relationship.
For example, a <tt class="docutils literal"><span class="pre">Blog</span></tt> object <tt class="docutils literal"><span class="pre">b</span></tt> has access to a list of all related
<tt class="docutils literal"><span class="pre">Entry</span></tt> objects via the <tt class="docutils literal"><span class="pre">entry_set</span></tt> attribute: <tt class="docutils literal"><span class="pre">b.entry_set.all()</span></tt>.</p>
<p>All examples in this section use the sample <tt class="docutils literal"><span class="pre">Blog</span></tt>, <tt class="docutils literal"><span class="pre">Author</span></tt> and <tt class="docutils literal"><span class="pre">Entry</span></tt>
models defined at the top of this page.</p>
<div class="section" id="s-one-to-many-relationships">
<span id="one-to-many-relationships"></span><h3>One-to-many relationships<a class="headerlink" href="#one-to-many-relationships" title="Permalink to this headline">¶</a></h3>
<div class="section" id="s-forward">
<span id="forward"></span><h4>Forward<a class="headerlink" href="#forward" title="Permalink to this headline">¶</a></h4>
<p>If a model has a <tt class="docutils literal"><span class="pre">ForeignKey</span></tt>, instances of that model will have access to
the related (foreign) object via a simple attribute of the model.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mf">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">blog</span> <span class="c"># Returns the related Blog object.</span>
</pre></div>
</div>
<p>You can get and set via a foreign-key attribute. As you may expect, changes to
the foreign key aren't saved to the database until you call <tt class="docutils literal"><span class="pre">save()</span></tt>.
Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mf">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">blog</span> <span class="o">=</span> <span class="n">some_blog</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>If a <tt class="docutils literal"><span class="pre">ForeignKey</span></tt> field has <tt class="docutils literal"><span class="pre">null=True</span></tt> set (i.e., it allows <tt class="docutils literal"><span class="pre">NULL</span></tt>
values), you can assign <tt class="xref docutils literal"><span class="pre">None</span></tt> to it. Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mf">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">blog</span> <span class="o">=</span> <span class="bp">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c"># "UPDATE blog_entry SET blog_id = NULL ...;"</span>
</pre></div>
</div>
<p>Forward access to one-to-many relationships is cached the first time the
related object is accessed. Subsequent accesses to the foreign key on the same
object instance are cached. Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mf">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">e</span><span class="o">.</span><span class="n">blog</span>  <span class="c"># Hits the database to retrieve the associated Blog.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">e</span><span class="o">.</span><span class="n">blog</span>  <span class="c"># Doesn't hit the database; uses cached version.</span>
</pre></div>
</div>
<p>Note that the <tt class="docutils literal"><span class="pre">select_related()</span></tt> <tt class="docutils literal"><span class="pre">QuerySet</span></tt> method recursively prepopulates
the cache of all one-to-many relationships ahead of time. Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">select_related</span><span class="p">()</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mf">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">e</span><span class="o">.</span><span class="n">blog</span>  <span class="c"># Doesn't hit the database; uses cached version.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">e</span><span class="o">.</span><span class="n">blog</span>  <span class="c"># Doesn't hit the database; uses cached version.</span>
</pre></div>
</div>
</div>
<div class="section" id="s-following-relationships-backward">
<span id="s-backwards-related-objects"></span><span id="following-relationships-backward"></span><span id="backwards-related-objects"></span><h4>Following relationships "backward"<a class="headerlink" href="#following-relationships-backward" title="Permalink to this headline">¶</a></h4>
<p>If a model has a <tt class="docutils literal"><span class="pre">ForeignKey</span></tt>, instances of the foreign-key model will have
access to a <tt class="docutils literal"><span class="pre">Manager</span></tt> that returns all instances of the first model. By
default, this <tt class="docutils literal"><span class="pre">Manager</span></tt> is named <tt class="docutils literal"><span class="pre">FOO_set</span></tt>, where <tt class="docutils literal"><span class="pre">FOO</span></tt> is the source
model name, lowercased. This <tt class="docutils literal"><span class="pre">Manager</span></tt> returns <tt class="docutils literal"><span class="pre">QuerySets</span></tt>, which can be
filtered and manipulated as described in the "Retrieving objects" section
above.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mf">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">entry_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span> <span class="c"># Returns all Entry objects related to Blog.</span>

<span class="go"># b.entry_set is a Manager that returns QuerySets.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">entry_set</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__contains</span><span class="o">=</span><span class="s">'Lennon'</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">entry_set</span><span class="o">.</span><span class="n">count</span><span class="p">()</span>
</pre></div>
</div>
<p>You can override the <tt class="docutils literal"><span class="pre">FOO_set</span></tt> name by setting the <tt class="docutils literal"><span class="pre">related_name</span></tt>
parameter in the <tt class="docutils literal"><span class="pre">ForeignKey()</span></tt> definition. For example, if the <tt class="docutils literal"><span class="pre">Entry</span></tt>
model was altered to <tt class="docutils literal"><span class="pre">blog</span> <span class="pre">=</span> <span class="pre">ForeignKey(Blog,</span> <span class="pre">related_name='entries')</span></tt>, the
above example code would look like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mf">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">entries</span><span class="o">.</span><span class="n">all</span><span class="p">()</span> <span class="c"># Returns all Entry objects related to Blog.</span>

<span class="go"># b.entries is a Manager that returns QuerySets.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">entries</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__contains</span><span class="o">=</span><span class="s">'Lennon'</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">entries</span><span class="o">.</span><span class="n">count</span><span class="p">()</span>
</pre></div>
</div>
<p>You cannot access a reverse <tt class="docutils literal"><span class="pre">ForeignKey</span></tt> <tt class="docutils literal"><span class="pre">Manager</span></tt> from the class; it must
be accessed from an instance:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">entry_set</span>
<span class="go">Traceback:</span>
<span class="go">    ...</span>
<span class="go">AttributeError: "Manager must be accessed via instance".</span>
</pre></div>
</div>
<p>In addition to the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> methods defined in "Retrieving objects" above,
the <tt class="docutils literal"><span class="pre">ForeignKey</span></tt> <tt class="docutils literal"><span class="pre">Manager</span></tt> has additional methods used to handle the set of
related objects. A synopsis of each is below, and complete details can be found
in the <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/models/relations/#ref-models-relations"><em>related objects reference</em></a>.</p>
<dl class="docutils">
<dt><tt class="docutils literal"><span class="pre">add(obj1,</span> <span class="pre">obj2,</span> <span class="pre">...)</span></tt></dt>
<dd>Adds the specified model objects to the related object set.</dd>
<dt><tt class="docutils literal"><span class="pre">create(**kwargs)</span></tt></dt>
<dd>Creates a new object, saves it and puts it in the related object set.
Returns the newly created object.</dd>
<dt><tt class="docutils literal"><span class="pre">remove(obj1,</span> <span class="pre">obj2,</span> <span class="pre">...)</span></tt></dt>
<dd>Removes the specified model objects from the related object set.</dd>
<dt><tt class="docutils literal"><span class="pre">clear()</span></tt></dt>
<dd>Removes all objects from the related object set.</dd>
</dl>
<p>To assign the members of a related set in one fell swoop, just assign to it
from any iterable object. Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">b</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mf">1</span><span class="p">)</span>
<span class="n">b</span><span class="o">.</span><span class="n">entry_set</span> <span class="o">=</span> <span class="p">[</span><span class="n">e1</span><span class="p">,</span> <span class="n">e2</span><span class="p">]</span>
</pre></div>
</div>
<p>If the <tt class="docutils literal"><span class="pre">clear()</span></tt> method is available, any pre-existing objects will be
removed from the <tt class="docutils literal"><span class="pre">entry_set</span></tt> before all objects in the iterable (in this
case, a list) are added to the set. If the <tt class="docutils literal"><span class="pre">clear()</span></tt> method is <em>not</em>
available, all objects in the iterable will be added without removing any
existing elements.</p>
<p>Each "reverse" operation described in this section has an immediate effect on
the database. Every addition, creation and deletion is immediately and
automatically saved to the database.</p>
</div>
</div>
<div class="section" id="s-many-to-many-relationships">
<span id="many-to-many-relationships"></span><h3>Many-to-many relationships<a class="headerlink" href="#many-to-many-relationships" title="Permalink to this headline">¶</a></h3>
<p>Both ends of a many-to-many relationship get automatic API access to the other
end. The API works just as a "backward" one-to-many relationship, above.</p>
<p>The only difference is in the attribute naming: The model that defines the
<tt class="docutils literal"><span class="pre">ManyToManyField</span></tt> uses the attribute name of that field itself, whereas the
"reverse" model uses the lowercased model name of the original model, plus
<tt class="docutils literal"><span class="pre">'_set'</span></tt> (just like reverse one-to-many relationships).</p>
<p>An example makes this easier to understand:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mf">3</span><span class="p">)</span>
<span class="n">e</span><span class="o">.</span><span class="n">authors</span><span class="o">.</span><span class="n">all</span><span class="p">()</span> <span class="c"># Returns all Author objects for this Entry.</span>
<span class="n">e</span><span class="o">.</span><span class="n">authors</span><span class="o">.</span><span class="n">count</span><span class="p">()</span>
<span class="n">e</span><span class="o">.</span><span class="n">authors</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">name__contains</span><span class="o">=</span><span class="s">'John'</span><span class="p">)</span>

<span class="n">a</span> <span class="o">=</span> <span class="n">Author</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mf">5</span><span class="p">)</span>
<span class="n">a</span><span class="o">.</span><span class="n">entry_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span> <span class="c"># Returns all Entry objects for this Author.</span>
</pre></div>
</div>
<p>Like <tt class="docutils literal"><span class="pre">ForeignKey</span></tt>, <tt class="docutils literal"><span class="pre">ManyToManyField</span></tt> can specify <tt class="docutils literal"><span class="pre">related_name</span></tt>. In the
above example, if the <tt class="docutils literal"><span class="pre">ManyToManyField</span></tt> in <tt class="docutils literal"><span class="pre">Entry</span></tt> had specified
<tt class="docutils literal"><span class="pre">related_name='entries'</span></tt>, then each <tt class="docutils literal"><span class="pre">Author</span></tt> instance would have an
<tt class="docutils literal"><span class="pre">entries</span></tt> attribute instead of <tt class="docutils literal"><span class="pre">entry_set</span></tt>.</p>
</div>
<div class="section" id="s-one-to-one-relationships">
<span id="one-to-one-relationships"></span><h3>One-to-one relationships<a class="headerlink" href="#one-to-one-relationships" title="Permalink to this headline">¶</a></h3>
<p>One-to-one relationships are very similar to many-to-one relationships. If you
define a <a title="django.db.models.OneToOneField" class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/models/fields/#django.db.models.OneToOneField"><tt class="xref docutils literal"><span class="pre">OneToOneField</span></tt></a> on your model, instances of
that model will have access to the related object via a simple attribute of the
model.</p>
<p>For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">EntryDetail</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">entry</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">OneToOneField</span><span class="p">(</span><span class="n">Entry</span><span class="p">)</span>
    <span class="n">details</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">TextField</span><span class="p">()</span>

<span class="n">ed</span> <span class="o">=</span> <span class="n">EntryDetail</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mf">2</span><span class="p">)</span>
<span class="n">ed</span><span class="o">.</span><span class="n">entry</span> <span class="c"># Returns the related Entry object.</span>
</pre></div>
</div>
<p>The difference comes in "reverse" queries. The related model in a one-to-one
relationship also has access to a <a title="django.db.models.Manager" class="reference external" href="http://docs.djangoproject.com/en/1.0/topics/db/managers/#django.db.models.Manager"><tt class="xref docutils literal"><span class="pre">Manager</span></tt></a> object, but
that <a title="django.db.models.Manager" class="reference external" href="http://docs.djangoproject.com/en/1.0/topics/db/managers/#django.db.models.Manager"><tt class="xref docutils literal"><span class="pre">Manager</span></tt></a> represents a single object, rather than
a collection of objects:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mf">2</span><span class="p">)</span>
<span class="n">e</span><span class="o">.</span><span class="n">entrydetail</span> <span class="c"># returns the related EntryDetail object</span>
</pre></div>
</div>
<p>If no object has been assigned to this relationship, Django will raise
a <tt class="docutils literal"><span class="pre">DoesNotExist</span></tt> exception.</p>
<p>Instances can be assigned to the reverse relationship in the same way as
you would assign the forward relationship:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">e</span><span class="o">.</span><span class="n">entrydetail</span> <span class="o">=</span> <span class="n">ed</span>
</pre></div>
</div>
</div>
<div class="section" id="s-how-are-the-backward-relationships-possible">
<span id="how-are-the-backward-relationships-possible"></span><h3>How are the backward relationships possible?<a class="headerlink" href="#how-are-the-backward-relationships-possible" title="Permalink to this headline">¶</a></h3>
<p>Other object-relational mappers require you to define relationships on both
sides. The Django developers believe this is a violation of the DRY (Don't
Repeat Yourself) principle, so Django only requires you to define the
relationship on one end.</p>
<p>But how is this possible, given that a model class doesn't know which other
model classes are related to it until those other model classes are loaded?</p>
<p>The answer lies in the <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-INSTALLED_APPS"><tt class="xref docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a> setting. The first time any model is
loaded, Django iterates over every model in <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-INSTALLED_APPS"><tt class="xref docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a> and creates the
backward relationships in memory as needed. Essentially, one of the functions
of <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-INSTALLED_APPS"><tt class="xref docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a> is to tell Django the entire model domain.</p>
</div>
<div class="section" id="s-queries-over-related-objects">
<span id="queries-over-related-objects"></span><h3>Queries over related objects<a class="headerlink" href="#queries-over-related-objects" title="Permalink to this headline">¶</a></h3>
<p>Queries involving related objects follow the same rules as queries involving
normal value fields. When specifying the value for a query to match, you may
use either an object instance itself, or the primary key value for the object.</p>
<p>For example, if you have a Blog object <tt class="docutils literal"><span class="pre">b</span></tt> with <tt class="docutils literal"><span class="pre">id=5</span></tt>, the following
three queries would be identical:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog</span><span class="o">=</span><span class="n">b</span><span class="p">)</span> <span class="c"># Query using object instance</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog</span><span class="o">=</span><span class="n">b</span><span class="o">.</span><span class="n">id</span><span class="p">)</span> <span class="c"># Query using id from instance</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog</span><span class="o">=</span><span class="mf">5</span><span class="p">)</span> <span class="c"># Query using id directly</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-falling-back-to-raw-sql">
<span id="falling-back-to-raw-sql"></span><h2>Falling back to raw SQL<a class="headerlink" href="#falling-back-to-raw-sql" title="Permalink to this headline">¶</a></h2>
<p>If you find yourself needing to write an SQL query that is too complex for
Django's database-mapper to handle, you can fall back into raw-SQL statement
mode.</p>
<p>The preferred way to do this is by giving your model custom methods or custom
manager methods that execute queries. Although there's nothing in Django that
<em>requires</em> database queries to live in the model layer, this approach keeps all
your data-access logic in one place, which is smart from an code-organization
standpoint. For instructions, see <a class="reference external" href="http://docs.djangoproject.com/en/1.0/topics/db/sql/#topics-db-sql"><em>Performing raw SQL queries</em></a>.</p>
<p>Finally, it's important to note that the Django database layer is merely an
interface to your database. You can access your database via other tools,
programming languages or database frameworks; there's nothing Django-specific
about your database.</p>
</div>
</div>



<div id="content-secondary">
  <h2 id="comments">Questions/Feedback</h2>
  <p>Having trouble? We'd like to help!</p>
  <ul>
    <li>
      Try the <a href="http://docs.djangoproject.com/en/dev/faq/">FAQ</a> — it's got answers to many common
      questions.
    </li>
    <li>
      Search for information in the <a href="http://groups.google.com/group/django-users/">archives of the
      django-users mailing list</a>, or <a href="http://groups.google.com/group/django-users/">post a question</a>.
    </li>
    <li>
      Ask a question in the <a href="irc://irc.freenode.net/">#django IRC
      channel</a>, or search the <a href="http://oebfare.com/logger/django/">IRC
      logs</a> to see if its been asked before.
    </li>
    <li>
      If you notice errors with this documentation, please <a href="http://code.djangoproject.com/simpleticket?component=Documentation">
      open a ticket</a> and let us know! Please only use the ticket tracker for
      criticisms and improvements on the docs. For tech support, use the
      resources above.
    </li>
  </ul>
</div>

		</div>
		<!-- END #content-main -->
		<div id="content-related" class="sidebar">
		
  
    <h2>Contents</h2>
    
      <ul>
<li><a class="reference external" href="">Making queries</a><ul>
<li><a class="reference external" href="#creating-objects">Creating objects</a></li>
<li><a class="reference external" href="#saving-changes-to-objects">Saving changes to objects</a><ul>
<li><a class="reference external" href="#saving-foreignkey-and-manytomanyfield-fields">Saving <tt class="docutils literal"><span class="pre">ForeignKey</span></tt> and <tt class="docutils literal"><span class="pre">ManyToManyField</span></tt> fields</a></li>
</ul>
</li>
<li><a class="reference external" href="#retrieving-objects">Retrieving objects</a><ul>
<li><a class="reference external" href="#retrieving-all-objects">Retrieving all objects</a></li>
<li><a class="reference external" href="#retrieving-specific-objects-with-filters">Retrieving specific objects with filters</a><ul>
<li><a class="reference external" href="#id1">Chaining filters</a></li>
<li><a class="reference external" href="#id2">Filtered QuerySets are unique</a></li>
<li><a class="reference external" href="#id3">QuerySets are lazy</a></li>
<li><a class="reference external" href="#other-queryset-methods">Other QuerySet methods</a></li>
</ul>
</li>
<li><a class="reference external" href="#id4">Limiting QuerySets</a></li>
<li><a class="reference external" href="#field-lookups">Field lookups</a></li>
<li><a class="reference external" href="#lookups-that-span-relationships">Lookups that span relationships</a><ul>
<li><a class="reference external" href="#spanning-multi-valued-relationships">Spanning multi-valued relationships</a></li>
</ul>
</li>
<li><a class="reference external" href="#the-pk-lookup-shortcut">The pk lookup shortcut</a></li>
<li><a class="reference external" href="#escaping-percent-signs-and-underscores-in-like-statements">Escaping percent signs and underscores in LIKE statements</a></li>
<li><a class="reference external" href="#id5">Caching and QuerySets</a></li>
</ul>
</li>
<li><a class="reference external" href="#complex-lookups-with-q-objects">Complex lookups with Q objects</a></li>
<li><a class="reference external" href="#comparing-objects">Comparing objects</a></li>
<li><a class="reference external" href="#deleting-objects">Deleting objects</a></li>
<li><a class="reference external" href="#updating-multiple-objects-at-once">Updating multiple objects at once</a></li>
<li><a class="reference external" href="#related-objects">Related objects</a><ul>
<li><a class="reference external" href="#one-to-many-relationships">One-to-many relationships</a><ul>
<li><a class="reference external" href="#forward">Forward</a></li>
<li><a class="reference external" href="#following-relationships-backward">Following relationships “backward”</a></li>
</ul>
</li>
<li><a class="reference external" href="#many-to-many-relationships">Many-to-many relationships</a></li>
<li><a class="reference external" href="#one-to-one-relationships">One-to-one relationships</a></li>
<li><a class="reference external" href="#how-are-the-backward-relationships-possible">How are the backward relationships possible?</a></li>
<li><a class="reference external" href="#queries-over-related-objects">Queries over related objects</a></li>
</ul>
</li>
<li><a class="reference external" href="#falling-back-to-raw-sql">Falling back to raw SQL</a></li>
</ul>
</li>
</ul>

    
  
  
  
    <h2>Search</h2>
    
    <form action="/en/1.0/search/" id="search" class="search">
  <div>
    <input name="cx" value="009763561546736975936:e88ek0eurf4" type="hidden">
    <input name="cof" value="FORID:11" type="hidden">
    <input name="ie" value="UTF-8" type="hidden">
    <input name="hl" value="" type="hidden">
    <input style="background: rgb(255, 255, 255) url(http://www.google.com/coop/intl/en/images/google_custom_search_watermark.gif) no-repeat scroll left center; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" id="id_search_q" class="query" name="q" type="text">
    <input name="sa" class="submit" value="Search" type="submit">
    <ul>
<li><label for="id_search_as_q_0"><input checked="checked" id="id_search_as_q_0" value="more:dev_docs" name="as_q" type="radio"> Latest</label></li>
<li><label for="id_search_as_q_1"><input id="id_search_as_q_1" value="more:1.0_docs" name="as_q" type="radio"> 1.0</label></li>
<li><label for="id_search_as_q_2"><input id="id_search_as_q_2" value="more:0.96_docs" name="as_q" type="radio"> 0.96</label></li>
<li><label for="id_search_as_q_3"><input id="id_search_as_q_3" value="more:all_docs" name="as_q" type="radio"> All</label></li>
</ul>
  </div>
</form>
<script type="text/javascript" src="Django%20%7C%20Making%20queries%20%7C%20Django%20Documentation_files/brand.html"></script>
  
  
  
    <h2>Browse</h2>
    <ul>
      
        
          <li>Prev: <a href="http://docs.djangoproject.com/en/1.0/topics/db/models/">Models</a></li>
        
        
          <li>Next: <a href="http://docs.djangoproject.com/en/1.0/topics/db/managers/">Managers</a></li>
        
        <li><a href="http://docs.djangoproject.com/en/1.0/contents/">Table of contents</a></li>
        
          <li><a href="http://docs.djangoproject.com/en/1.0/genindex/">General Index</a></li>
        
          <li><a href="http://docs.djangoproject.com/en/1.0/modindex/">Global Module Index</a></li>
        
      
    </ul>
  
  
  
    <h2>You are here:</h2>
    <ul>
      
        <li>
          <a href="http://docs.djangoproject.com/en/1.0/">Django 1.0 documentation</a>
          
            <ul><li><a href="http://docs.djangoproject.com/en/1.0/topics/">Using Django</a>
          
            <ul><li><a href="http://docs.djangoproject.com/en/1.0/topics/db/">Models and databases</a>
          
          <ul><li>Making queries</li></ul>
          </li></ul></li></ul>
        </li>
      
    </ul>
  
  
  
    <h3>Last update:</h3>
    <div>May 23, 2009, 8:15 a.m. (<a href="http://www.timeanddate.com/worldclock/city.html?n=64">CDT</a>)</div>
  

		</div>
		<!-- END #content-related -->

		</div>
		<!-- END #content -->
		<div id="footer">
			<p>© 2005-2009 <a href="http://www.djangoproject.com/foundation/">Django Software Foundation</a> unless otherwise noted. Django is a registered trademark of the Django Software Foundation. 
			Hosting graciously provided by <a href="http://mediatemple.net/">
			<img style="vertical-align: middle; position: relative; top: -1px;" src="Django%20%7C%20Making%20queries%20%7C%20Django%20Documentation_files/mt.png" alt="media temple"></a>
			</p>
		</div>
		<!-- END #footer -->
	</div>
	<!-- END #container -->
	</body></html>